package com.example.permissionservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.constant.RoleConstant;
import com.example.common.dto.ApiResponse;
import com.example.common.enums.ErrorCodeEnum;
import com.example.common.exception.BusinessException;
import com.example.permissionservice.entity.Role;
import com.example.permissionservice.entity.UserRole;
import com.example.permissionservice.mapper.RoleMapper;
import com.example.permissionservice.mapper.UserRoleMapper;
import com.example.permissionservice.service.PermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class PermissionServiceImpl implements PermissionService {

    private final RoleMapper roleMapper;
    private final UserRoleMapper userRoleMapper;

    /**
     * 绑定默认角色
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse<Void> bindDefaultRole(Long userId) {
        //获取普通用户角色
        Role role = roleMapper.findByCode(RoleConstant.USER);
        if (role == null){
            throw new BusinessException(ErrorCodeEnum.ROLE_NOT_FOUND,"角色不存在");
        }

        //检查角色是否已绑定
        UserRole userRole = userRoleMapper.findByUserId(userId);
        if (userRole != null){
            return ApiResponse.success(null);
        }

        //用户未绑定，创建绑定关系，插入数据库
        //角色绑定默认绑定普通用户角色，需要管理员身份需超级管理员调用升级接口
        updateUserRole(userId, role.getRoleId());

        return ApiResponse.success(null);
    }

    /**
     * 获取用户角色码
     * @param userId
     * @return
     */
    @Override
    public ApiResponse<String> getUserRoleCode(Long userId) {
        //获取角色码
        String roleCode = userRoleMapper.getRoleCodeByUserId(userId);

        //如果该用户没有绑定角色码，返回默认角色
        if (roleCode == null){
            roleCode = RoleConstant.USER;
        }

        return ApiResponse.success(roleCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse<Void> upgradeToAdmin(Long userId) {
        // 获取管理员角色
        Role role = roleMapper.findByCode(RoleConstant.ADMIN);
        if (role == null) {
            throw new BusinessException(ErrorCodeEnum.ROLE_NOT_FOUND, "管理员角色不存在");
        }

        // 更新用户角色
        updateUserRole(userId, role.getRoleId());

        return ApiResponse.success(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse<Void> downgradeToUser(Long userId) {
        //获取普通用户角色
        Role role = roleMapper.findByCode(RoleConstant.USER);
        if (role == null){
            throw new BusinessException(ErrorCodeEnum.ROLE_NOT_FOUND,"角色不存在");
        }

        //更新用户角色
        updateUserRole(userId, role.getRoleId());

        return ApiResponse.success(null);
    }

    //更新用户信息
    private void updateUserRole(Long userId, Integer roleId) {
        //检查角色是否存在
        UserRole userRole = userRoleMapper.findByUserId(userId);
        if (userRole == null){
            userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRoleMapper.insert(userRole);
        }else {
            //更新用户角色
            userRole.setRoleId(roleId);
            userRoleMapper.updateById(userRole);
        }
    }
}